from rest_framework import serializers
from user.models import SysUser  # 使用项目的真实用户模型
from .models import UserChatRoom, UserChatMessage


class UserSimpleSerializer(serializers.ModelSerializer):
    """用户简单序列化器"""
    display_name = serializers.SerializerMethodField()
    is_online = serializers.SerializerMethodField()
    avatar_url = serializers.SerializerMethodField()
    
    class Meta:
        model = SysUser
        fields = ['id', 'username', 'email', 'avatar', 'display_name', 'is_online', 'avatar_url']
    
    def get_display_name(self, obj):
        """获取用户显示名称"""
        return obj.username
    
    def get_is_online(self, obj):
        """获取用户在线状态（简化版）"""
        # 简化版：所有用户都显示为在线
        # 实际可以根据最后活动时间判断
        return obj.status == 0
    
    def get_avatar_url(self, obj):
        """获取用户头像链接"""
        if obj.avatar:
            return obj.avatar
        # 返回默认头像或根据用户名生成的头像
        return f"https://ui-avatars.com/api/?name={obj.username}&background=667eea&color=fff"


class UserChatMessageSerializer(serializers.ModelSerializer):
    """聊天消息序列化器"""
    sender = UserSimpleSerializer(read_only=True)
    sender_id = serializers.IntegerField(write_only=True, required=False)
    
    class Meta:
        model = UserChatMessage
        fields = ['id', 'room', 'sender', 'sender_id', 'content', 'message_type', 'timestamp']
        read_only_fields = ['timestamp']
    
    def create(self, validated_data):
        # 如果没有指定sender_id，使用当前请求用户
        request = self.context.get('request')
        if 'sender_id' in validated_data:
            validated_data['sender'] = SysUser.objects.get(id=validated_data.pop('sender_id'))
        elif request:
            # 尝试从请求中获取当前用户
            from .user_session import user_session_manager
            current_user = user_session_manager.get_current_user_from_request(request)
            if current_user:
                validated_data['sender'] = current_user
            else:
                # 默认值（不推荐）
                validated_data['sender'] = SysUser.objects.get(id=1)
        
        return super().create(validated_data)


class UserChatRoomSerializer(serializers.ModelSerializer):
    """聊天室序列化器"""
    participants = UserSimpleSerializer(many=True, read_only=True)
    participant_ids = serializers.ListField(
        child=serializers.IntegerField(),
        write_only=True,
        required=False
    )
    last_message = UserChatMessageSerializer(read_only=True)
    other_participant = serializers.SerializerMethodField()
    
    class Meta:
        model = UserChatRoom
        fields = ['id', 'room_type', 'participants', 'participant_ids', 'created_at', 'updated_at', 'last_message', 'other_participant']
        read_only_fields = ['created_at', 'updated_at']
    
    def get_other_participant(self, obj):
        """获取对话中的另一个参与者（适用于一对一聊天）"""
        request = self.context.get('request')
        if request and obj.room_type == 'private':
            current_user = None
            
            # 方法1: 从请求参数获取用户ID
            current_user_id = request.query_params.get('current_user_id')
            if current_user_id:
                try:
                    current_user = SysUser.objects.get(id=current_user_id, status=0)
                except SysUser.DoesNotExist:
                    pass
            
            # 方法2: 使用用户会话管理器（fallback）
            if not current_user:
                from .user_session import user_session_manager
                current_user = user_session_manager.get_current_user_from_request(request)
            
            if current_user:
                other_user = obj.get_other_participant(current_user)
                if other_user:
                    return UserSimpleSerializer(other_user).data
        return None
    
    def create(self, validated_data):
        participant_ids = validated_data.pop('participant_ids', [])
        request = self.context.get('request')
        
        # 创建聊天室
        room = UserChatRoom.objects.create(**validated_data)
        
        # 添加参与者
        if participant_ids:
            participants = SysUser.objects.filter(id__in=participant_ids)
            room.participants.set(participants)
        
        # 如果有当前用户且不在参与者中，添加当前用户
        # 这里临时使用默认用户ID 1（后续会修改）
        current_user_id = 1  # 临时默认值
        if current_user_id:
            current_user = SysUser.objects.get(id=current_user_id)
            room.participants.add(current_user)
        
        return room


class UserChatRoomListSerializer(serializers.ModelSerializer):
    """聊天室列表序列化器（简化版）"""
    other_participant = serializers.SerializerMethodField()
    last_message = UserChatMessageSerializer(read_only=True)
    unread_count = serializers.SerializerMethodField()
    
    class Meta:
        model = UserChatRoom
        fields = ['id', 'room_type', 'other_participant', 'last_message', 'updated_at', 'unread_count']
    
    def get_other_participant(self, obj):
        """获取对话中的另一个参与者"""
        request = self.context.get('request')
        if request and obj.room_type == 'private':
            current_user = None
            
            # 方法1: 从请求参数获取用户ID
            current_user_id = request.query_params.get('current_user_id')
            if current_user_id:
                try:
                    current_user = SysUser.objects.get(id=current_user_id, status=0)
                except SysUser.DoesNotExist:
                    pass
            
            # 方法2: 使用用户会话管理器（fallback）
            if not current_user:
                from .user_session import user_session_manager
                current_user = user_session_manager.get_current_user_from_request(request)
            
            if current_user:
                other_user = obj.get_other_participant(current_user)
                if other_user:
                    return UserSimpleSerializer(other_user).data
        return None
    
    def get_unread_count(self, obj):
        """获取未读消息数量（暂时返回0，后续可扩展）"""
        return 0